import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api'

export default {
    namespaced: true,
    state: {
        cartList: []
    },
    actions: {
        //获取购物车列表
        async getCartList({ commit }) {
            let result = await reqCartList();
            if (result.code == 200) {
                commit('GETCARTLIST', result.data)
                console.log(result);
            }
        },
        //删除购物车某一个产品
        async deleteCartList({ commit }, skuId) {
            let result = await reqDeleteCartById(skuId);
            if (result.code == 200) {
                //没有返回数据,不用三联
                return "ok"
            } else {
                return Promise.reject(new Error('Fail'))
            }
        },
        //删除选中的全部产品 普通方法
        // deleteAllCheckedCart({ dispatch, getters }) {
        //     getters.cartList.cartInfoList.forEach(element => {
        //         console.log(element);
        //         element.isChecked == 1 ? dispatch('deleteCartList', element.skuId) : '';
        //     });
        // },
        //删除选中的全部产品 Promise方法
        deleteAllCheckedCart({ dispatch, getters }) {
            let PromiseAll = []
            getters.cartList.cartInfoList.forEach(element => {
                let promise = element.isChecked == 1 ? dispatch('deleteCartList', element.skuId) : '';
                //将每一次返回的Promise添加到数组当中
                PromiseAll.push(promise);
            });
            //返回
            return Promise.all(PromiseAll)
        },

        //修改购物车某一个产品的选中状态
        async updatedCheckedById({ commit }, { skuId, isChecked }) {
            let result = await reqUpdateCheckedById(skuId, isChecked)
            if (result.code == 200) {
                //没有返回数据,不用三联
                return "ok"
            } else {
                return Promise.reject(new Error('Fail'))
            }
        },

        //全选。全不选
        updateAllCartIsChecked({ dispatch, state }, isChecked) {
            let PromiseAll = []
            //修改全部产品的状态
            state.cartList[0].cartInfoList.forEach(element => {
                let promise = dispatch('updatedCheckedById', { skuId: element.skuId, isChecked: isChecked })
                PromiseAll.push(promise);
            });
            return Promise.all(PromiseAll)
        }
    },
    mutations: {
        GETCARTLIST(state, cartList) {
            state.cartList = cartList
        }
    },
    getters: {
        cartList(state) {
            return state.cartList[0] || {}
        }
    },

}